package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.dao.UserInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.UserInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.model.UserSessionInfo;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.base.Header;
import cc.rengu.igas.bsps.facade.request.UserPasswordModifyRequest;
import cc.rengu.igas.bsps.facade.response.UserPasswordModifyResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.enums.PinTypeEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.PasswordInfo;
import cc.rengu.oltp.service.realize.SafeKeyBoardService;
import cc.rengu.oltp.service.realize.impl.SafeKeyBoardServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.RedisUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 功能：用户密码修改
 *
 * @author 赵奎伍
 * @date 2020/4/5
 */
public class UserPasswordModifyService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        UserPasswordModifyRequest userInfoModifyRequest = new UserPasswordModifyRequest();
        ConvertUtil.convertOutput(userInfoModifyRequest);
        return userInfoModifyRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        UserPasswordModifyRequest requestParams = (UserPasswordModifyRequest) request;
        String instId = requestParams.getHeader().getInstId();
        String userId = requestParams.getUserId();
        String passwordType = requestParams.getPasswordType();//密码类型
        String password = requestParams.getPassword();//旧密码
        String newPassword = requestParams.getNewPassword();//新密码
        String confirmPassword = requestParams.getConfirmPassword();//确认新密码
        String chanlId = requestParams.getHeader().getChanlId();
        if (StringUtil.isEmptyOrNull(passwordType) || StringUtil.isEmptyOrNull(password) || StringUtil.isEmptyOrNull(newPassword) || StringUtil.isEmptyOrNull(confirmPassword)) {
            rglog.error("必填性校验失败");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        //将新密码进行处理
        SafeKeyBoardService safeKeyBoardService = new SafeKeyBoardServiceImpl();
        //校验旧密码是否一致
        UserInfoMapper userInfoMapper = new UserInfoMapperImpl();
        UserInfo userInfo = userInfoMapper.selectBspUserInfoByPrimaryKey(instId, userId);
        if (null == userInfo) {
            rglog.error("用户<{}>信息不存在!", requestParams.getUserId());
            throw new BizException(RespCodeEnum.GET_USER_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_INFO_ERROR.getRespDesc());
        }
        PasswordInfo passwordInfo = new PasswordInfo(requestParams.getMchntNo(), PinTypeEnum.MIXED, password);
        PasswordInfo newPasswordInfo = new PasswordInfo(requestParams.getMchntNo(), PinTypeEnum.MIXED, newPassword);
        PasswordInfo confirmPasswordInfo = new PasswordInfo(requestParams.getMchntNo(), PinTypeEnum.MIXED, confirmPassword);
        if (chanlId.equals("PCWEB")) {
            Header header = requestParams.getHeader();
            UserSessionInfo keySessionInfo = JSON.parseObject(RedisUtil.onceGet(header.getSession()), UserSessionInfo.class);
            if (null == keySessionInfo) {
                rglog.error("session为空");
                throw new BizException(RespCodeEnum.USER_NOT_LOGIN_OR_SESSION_IS_EXPIRED.getRespCode(), RespCodeEnum.USER_NOT_LOGIN_OR_SESSION_IS_EXPIRED.getRespDesc());
            }
            String randomString = keySessionInfo.getRandomString();
            keySessionInfo.setRandomString("");
            RedisUtil.onceSet(header.getSession(), JSONObject.toJSONString(keySessionInfo), BspsAppParamConstant.SESSION_EFFECTIVE_TIME);

            if ("00".equals(passwordType)) {
                rglog.info("PC端修改登录密码");
                //00-登录密码
                if (!passwordInfo.getPasswordValue().trim().equalsIgnoreCase(userInfo.getLoginPassword())) {
                    rglog.error("原密码错误");
                    throw new BizException(RespCodeEnum.ORIGINAL_PASSWORD_MODIFY_ERROR.getRespCode(), RespCodeEnum.ORIGINAL_PASSWORD_MODIFY_ERROR.getRespDesc());
                }
                //前端已校验，服务端二次校验
                if (!newPassword.equalsIgnoreCase(confirmPassword)) {
                    rglog.error("新密码错误与确认新密码不一致");
                    throw new BizException(RespCodeEnum.PASSWORD_CHECK_ERROR.getRespCode(), RespCodeEnum.PASSWORD_CHECK_ERROR.getRespDesc());
                }
                //校验新密码不能与上次密码一致
                if (newPasswordInfo.getPasswordValue().trim().equalsIgnoreCase(userInfo.getLoginPassword())) {
                    rglog.error("校验新密码不能与上次密码一致");
                    throw new BizException(RespCodeEnum.PASSWORD_REPEAT_MODIFY_ERROR.getRespCode(), RespCodeEnum.PASSWORD_REPEAT_MODIFY_ERROR.getRespDesc());
                }
                userInfo.setLoginPassword(newPasswordInfo.getPasswordValue().trim());
            } else if ("01".equals(passwordType)) {
                rglog.info("PC端修改交易密码");
                if (!passwordInfo.getPasswordValue().trim().equalsIgnoreCase(userInfo.getTransPassword())) {
                    //校验上送原密码和库中存在的密码是否一致
                    rglog.error("原密码错误");
                    throw new BizException(RespCodeEnum.ORIGINAL_PASSWORD_MODIFY_ERROR.getRespCode(), RespCodeEnum.ORIGINAL_PASSWORD_MODIFY_ERROR.getRespDesc());
                }
                //前端已校验，服务端二次校验
                if (!newPassword.equalsIgnoreCase(confirmPassword)) {
                    rglog.error("新密码错误与确认新密码不一致");
                    throw new BizException(RespCodeEnum.PASSWORD_CHECK_ERROR.getRespCode(), RespCodeEnum.PASSWORD_CHECK_ERROR.getRespDesc());
                }
                //校验新密码不能与上次密码一致
                if (newPasswordInfo.getPasswordValue().trim().equalsIgnoreCase(userInfo.getTransPassword())) {
                    rglog.error("校验新密码不能与上次密码一致");
                    throw new BizException(RespCodeEnum.PASSWORD_REPEAT_MODIFY_ERROR.getRespCode(), RespCodeEnum.PASSWORD_REPEAT_MODIFY_ERROR.getRespDesc());
                }
                /* 01-交易密码 */
                userInfo.setTransPassword(newPasswordInfo.getPasswordValue().trim());
            } else {
                rglog.error("不支持的参数设置类型:<{}>", passwordType);
                throw new BizException(RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespCode(), RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespDesc());
            }
        } else {
            if ("00".equals(passwordType)) {
                rglog.info("非PC端修改登录密码");
                password = safeKeyBoardService.encryptPassword(instId, null, passwordInfo, null);
                newPassword = safeKeyBoardService.encryptPassword(instId, null, newPasswordInfo, null);
                confirmPassword = safeKeyBoardService.encryptPassword(instId, null, confirmPasswordInfo, null);
                rglog.info("password:<{}>,newPassword:<{}>,confirmPassword:<{}>", password, newPassword, confirmPassword);
                //00-登录密码
                if (!passwordInfo.getPasswordValue().trim().equalsIgnoreCase(userInfo.getLoginPassword())) {
                    //校验上送原密码和库中存在的密码是否一致
                    rglog.error("原密码错误");
                    throw new BizException(RespCodeEnum.ORIGINAL_PASSWORD_MODIFY_ERROR.getRespCode(), RespCodeEnum.ORIGINAL_PASSWORD_MODIFY_ERROR.getRespDesc());
                }
                if (!newPassword.equalsIgnoreCase(confirmPassword)) {
                    rglog.error("用户上送的两次新密码不一致，不允许更新此密码，交易失败");
                    throw new BizException(RespCodeEnum.PASSWORD_INCONSISTENCY.getRespCode(), RespCodeEnum.PASSWORD_INCONSISTENCY.getRespDesc());
                }
                //校验新密码不能与上次密码一致
                if (newPasswordInfo.getPasswordValue().trim().equalsIgnoreCase(userInfo.getLoginPassword())) {
                    rglog.error("校验新密码不能与上次密码一致");
                    throw new BizException(RespCodeEnum.PASSWORD_REPEAT_MODIFY_ERROR.getRespCode(), RespCodeEnum.PASSWORD_REPEAT_MODIFY_ERROR.getRespDesc());
                }
                userInfo.setLoginPassword(newPasswordInfo.getPasswordValue().trim());
            } else if ("01".equals(passwordType)) {
                rglog.info("非PC端修改交易密码");
                password = safeKeyBoardService.encryptPassword(instId, null, passwordInfo, null);
                newPassword = safeKeyBoardService.encryptPassword(instId, null, newPasswordInfo, null);
                confirmPassword = safeKeyBoardService.encryptPassword(instId, null, confirmPasswordInfo, null);
                rglog.info("password:<{}>,newPassword:<{}>,confirmPassword:<{}>", password, newPassword, confirmPassword);
                if (!passwordInfo.getPasswordValue().trim().equalsIgnoreCase(userInfo.getTransPassword())) {
                    //校验上送原密码和库中存在的密码是否一致
                    rglog.error("原密码错误");
                    throw new BizException(RespCodeEnum.ORIGINAL_PASSWORD_MODIFY_ERROR.getRespCode(), RespCodeEnum.ORIGINAL_PASSWORD_MODIFY_ERROR.getRespDesc());
                }
                if (!newPassword.equalsIgnoreCase(confirmPassword)) {
                    rglog.error("用户上送的两次新密码不一致，不允许更新此密码，交易失败");
                    throw new BizException(RespCodeEnum.PASSWORD_INCONSISTENCY.getRespCode(), RespCodeEnum.PASSWORD_INCONSISTENCY.getRespDesc());
                }
                //校验新密码不能与上次密码一致
                if (newPasswordInfo.getPasswordValue().trim().equalsIgnoreCase(userInfo.getTransPassword())) {
                    rglog.error("校验新密码不能与上次密码一致");
                    throw new BizException(RespCodeEnum.PASSWORD_REPEAT_MODIFY_ERROR.getRespCode(), RespCodeEnum.PASSWORD_REPEAT_MODIFY_ERROR.getRespDesc());
                }
                userInfo.setTransPassword(newPasswordInfo.getPasswordValue().trim());
            } else {
                rglog.error("不支持的参数设置类型:<{}>", passwordType);
                throw new BizException(RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespCode(), RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespDesc());
            }
        }

        //更新数据到用户信息表
        userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        userInfo.setLastOprId(userId);
        int iReturnCode = userInfoMapper.updateBspUserInfoByPrimaryKey(userInfo);
        if (0 != iReturnCode) {
            rglog.error("更新用户<{}>密码失败!新密码");
            throw new BizException(RespCodeEnum.UPDATE_USER_INFO_ERROR.getRespCode(), RespCodeEnum.UPDATE_USER_INFO_ERROR.getRespDesc());
        }

        /* 拼装应答报文 */
        UserPasswordModifyResponse userPasswordModifyResponse = new UserPasswordModifyResponse();
        BizResponse<UserPasswordModifyResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(userPasswordModifyResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        UserPasswordModifyResponse userInfoModifyResponse = (UserPasswordModifyResponse) bizResponse.getResult();
        ConvertUtil.convertInput(userInfoModifyResponse);
    }
}
